// formPackage/pages/article/newsList/newsList.js
let template = require('./../../template/tabbar.js');


// shopMallPackage/pages/shopCarList/shopCarList.js
import { addCartNumRequest, delCartRequest } from "../../service/onetoone_service"
import {
  GWCEMPTY_IMG
} from "../../service/image_service"
import {
  queryCartCount,
  queryCartList,
  cartGoodNumChange,
  deleteCartGoods
} from "../../service/jb_shopcar_service.js"
import mathUtil from '../../tools/mathUtils/mathUtil.js'
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    gwcEmpty_img: GWCEMPTY_IMG,
    cartList: [],
    isAll: false,
    totalMoney: 0,
    isEditStatus: false,
    cartPage: 1,
    cartLimit: 10,
    refreshFlag: false,
    cartTotalNum: 0,
    isSelectNum: 0,//当前选中的商品
    isShowLoading: false,//加载状态出现
    isBottomShow: false,//是否没有更多数据了
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    template.tabbar("tabBar", 2, this, app.globalData.cartNum)//0表示第一个tabbar
    wx.hideTabBar();

  },



  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //购物车是私人数据，需要登录了才能调用
    if (app.globalData.isLogin) {
      this.queryCartList('refresh');
      this.queryCartCount();
    }

  },
  editStatusChange() {
    this.setData({
      isEditStatus: !this.data.isEditStatus
    })
  },
  cancelQueryList() {
    queryCartList().then(res => {
      wx.hideLoading();
      console.log("JJLog:购物车列表是:" + JSON.stringify(res));
      if (res.code == 200) {
        let arr = res.data || [];
        if (arr && arr.length > 0) {
          arr.forEach((item, index) => {
            item.isChoose = this.data.cartList[index].isChoose
          })
          this.setData({
            cartList: [],
          })
          this.setData({
            cartList: arr
          })
        }
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || '查询失败',
        icon: "none"
      })
      console.log("JJLog:queryCartList", err);
    })
  },
  //跳转到商品详情：
  pushToProductDetail(e) {
    let productId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: "/shopMallPackage/pages/newStoreDetail/newStoreDetail?productId=" + productId,
    })
  },
  queryCartList(type) {
    wx.showLoading();
    queryCartList(this.data.cartPage, this.data.cartLimit).then(res => {
      wx.hideLoading();
      console.log("JJLog:购物车列表是:" + JSON.stringify(res));
      if (res.code == 200 && res.data.list && res.data.list.length > 0) {
        let arr = (type == 'refresh' ? [] : this.data.cartList || []);
        res.data.list.forEach((item) => {
          item.isChoose = false;
        })
        arr = arr.concat(res.data.list)
        this.setData({
          cartList: arr,
          refreshFlag: false,
          isShowLoading: false,
          isBottomShow: res.data.totalPage == this.data.cartPage ? true : false,
        })
        if (type == 'refresh') {
          this.setData({
            isAll: false,
            totalMoney: 0,
          })
        }
      } else {
        this.setData({
          cartList: [],
          isAll: false,
          totalMoney: 0,
          isShowLoading: false,
          refreshFlag: false,
        })
      }




    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || '查询失败',
        icon: "none"
      })
      if (this.data.cartPage != 1) {
        this.setData({
          cartPage: this.data.cartPage - 1
        })
      }
      this.setData({
        refreshFlag: false,
      })
      console.log("JJLog:queryCartList", err);
    })
  },
  //查询购物车数量
  queryCartCount() {
    queryCartCount().then(res => {
      console.log("JJLog:查询购物车数量" + JSON.stringify(res));
      if (res.code == 200) {
        this.setData({
          cartTotalNum: res.data.count
        })
        app.globalData.cartNum = res.data.count || 0;
        template.tabbar("tabBar", 2, this, app.globalData.cartNum)//0表示第一个tabbar
      }
    }).catch(err => {
      console.log("JJLog:queryCartCount", err);
    })
  },

  // 全选操作:
  allSelectAction() {
    //已经全选
    if (this.data.isAll) {
      let arr = this.data.cartList;
      arr.forEach((item) => {
        item.isChoose = false
      })
      this.setData({
        cartList: arr,
        isAll: false,
        totalMoney: 0,
        isSelectNum: 0,
      })
    } else {
      // 未全选:
      let money = 0;
      let arr = this.data.cartList;
      let noSe = 0
      arr.forEach((item) => {
        if (item.attrStatus) {
          item.isChoose = true;
          let mulValue = mathUtil.mul(item.price, item.cartNum);
          money = mathUtil.add(money, mulValue)
        } else {
          item.isChoose = false;
          noSe = noSe + 1
        }

      })
      this.setData({
        cartList: arr,
        isAll: true,
        totalMoney: money,
        isSelectNum: this.data.cartList.length - noSe
      })
    }
  },
  // 单个选中：
  singleSelectAction(e) {
    let totalMoney = this.data.totalMoney;
    let index = e.currentTarget.dataset.index;
    let item = e.currentTarget.dataset.item;
    let isChoose = !item.isChoose
    //动态数组:
    let changeItem = 'cartList[' + index + '].isChoose';
    this.setData({
      [changeItem]: isChoose,
    })
    let middleValue = mathUtil.mul(item.price, item.cartNum)
    // true 加
    if (isChoose) {

      totalMoney = mathUtil.add(totalMoney, middleValue)
    } else {
      // 减
      totalMoney = mathUtil.sub(totalMoney, middleValue)
    }
    this.setData({
      totalMoney: totalMoney
    })

    // 是否全选:
    this.isAllAction();
  },
  isAllAction() {
    let arr = this.data.cartList;
    let selectNum = 0;
    arr.forEach((item) => {
      if (item.isChoose) {
        selectNum = selectNum + 1;
      }
    })
    this.setData({
      isSelectNum: selectNum
    })
    if (selectNum == this.data.cartList.length) {
      this.setData({
        isAll: true
      })
    } else {
      this.setData({
        isAll: false
      })
    }
  },
  //加载更多购物车数据
  handleLoadmore() {
    if (!app.globalData.isLogin) {
      return;
    }
    console.log('加载更多');
    if (this.data.isBottomShow) {
      return;
    }
    this.setData({
      isShowLoading: true,
      cartPage: this.data.cartPage + 1
    })
    this.queryCartList('')
  },
  //下拉刷新
  handleRefresh() {

    this.setData({
      refreshFlag: true,
      cartPage: 1,
      isBottomShow: false,
    })
    if (!app.globalData.isLogin) {
      setTimeout(() => {
        this.setData({
          refreshFlag: false,
        })
      }, 1500)
      return;
    }


    this.queryCartList('refresh');
  },


  // 数量加减变化：
  onChangePrice(e) {
    let totalMoney = this.data.totalMoney;
    let index = e.currentTarget.dataset.index;
    let item = e.currentTarget.dataset.item;
    let originNum = item.cartNum;
    let num = e.detail;
    cartGoodNumChange({ id: item.id, number: num }).then(res => {
      console.log("JJLog:操作成功:" + JSON.stringify(res));
      if (res.code == 200) {
        //动态数组:
        let changeItem = 'cartList[' + index + '].cartNum';
        this.setData({
          [changeItem]: num,
        })
        // 已经选中才影响总价
        if (item.isChoose) {
          if (originNum < num) {
            // 加:
            totalMoney = mathUtil.add(totalMoney, item.price);
          } else {
            // 减:
            totalMoney = mathUtil.sub(totalMoney, item.price)
          }
          this.setData({
            totalMoney: totalMoney
          })

        }
      }
    }).catch(err => {
      wx.showToast({
        title: err || "操作失败",
        icon: "none"
      })
      let changeItem = 'cartList[' + index + '].cartNum';
      this.setData({
        [changeItem]: num - 1,
      })
      console.error("JJLog:cartGoodNumChange:", err);
    })

  },

  //删除购物车中的商品
  deleteGoodsAction() {
    //删除的商品ids 逗号拼接
    if (this.data.isSelectNum == 0) {
      wx.showToast({
        title: '请选择要删除的商品',
        icon: "none"
      })
      return;
    }
    let idArr = [];
    let ids = "";
    // let ids = this.data.cartList.map((item) => {
    //   if (item.isChoose) {
    //     return item.id
    //   }
    // }).join(",");
    this.data.cartList.forEach(i => {
      if (i.isChoose) {
        idArr.push(i.id);
      }
    })
    ids = idArr.join(',')
    console.log("JJLog:哈哈哈：" + ids);
    if (ids == '') {
      wx.showToast({
        title: '请选择要删除的商品',
        icon: "none"
      })
      return;
    }
    wx.showLoading();
    deleteCartGoods({ ids: ids }).then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        this.queryCartList('refresh');
        this.queryCartCount();
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || '删除失败',
        icon: "none"
      })
      console.error("JJLog:deleteCartGoods:", err);
    })
  },

  // 删除一个购物车:
  cancelOneCon(e) {
    let totalMoney = this.data.totalMoney;
    let index = e.currentTarget.dataset.index;
    let arr = this.data.cartList;
    let item = e.currentTarget.dataset.item;
    let originNum = item.cartNum;
    wx.showLoading({
      title: '删除中...',
    })
    delCartRequest(item.id).then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        if (item.isChoose) {
          totalMoney = (totalMoney * 100 - item.price * 100 * originNum) / 100;
          this.setData({
            totalMoney: totalMoney,
          })
        }
        arr.splice(index, 1);
        this.setData({
          cartList: arr,
        })
        this.cancelQueryList();
        this.isAllAction();
      }

    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || '删除失败',
        icon: "none"
      })
      console.error("JJLog:cancelOneCon", err);
    })
  },
  // 去结算
  goToSettleAction() {
    if (this.data.totalMoney < 0 || this.data.totalMoney == 0) {
      wx.showToast({
        title: '请选择要结算的商品',
        icon: "none"
      })
      return;
    }
    let arr = this.data.cartList;
    let sArr = [];
    arr.forEach((item) => {
      if (item.isChoose) {
        sArr.push(item)
      }
    })
    app.globalData.cartList = sArr;
    app.globalData.cartMoney = this.data.totalMoney;
    console.log("JJLog:要结算的是:" + JSON.stringify(app.globalData.cartList));
    app.globalData.jiesuanInfo = {
      cartList: sArr,
    }
    wx.navigateTo({
      url: '/featurePackage/pages/submitOrder/submitOrder?type=shoppingCart',
    })
  },

})